package nl.gamayun.whohasit.services;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import nl.gamayun.whohasit.Loan;
import nl.gamayun.whohasit.LoanActivity;
import nl.gamayun.whohasit.R;
import nl.gamayun.whohasit.WhoHasIt;
import nl.gamayun.whohasit.WhoHasItHandler;
import nl.gamayun.whohasit.utils.WhoHasItUtils;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class WhoHasItService extends Service {

	static final String TAG = WhoHasItService.class.getSimpleName();
	static final int DELAY = 60000;
	private boolean runFlag = false;
	private Updater updater;
	private WhoHasIt whoHasIt;
	private List<Long> notified = new ArrayList<Long>();
	
	public static final String TO_LATE_INTENT = "nl.gamayun.whohasit.TO_LATE";
	public static final String TO_LATE_LOAN = "TO_LATE_LOAN";
	public static final String TO_LATE_NOTIFICATIONS = "nl.gamayun.whohasit.TO_LATE_NOTIFICATIONS";
	

	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onCreate() {
		Log.d(TAG, "onCreated");
		super.onCreate();
		this.whoHasIt = (WhoHasIt) getApplication();
		this.updater = new Updater();
		WhoHasItUtils.getWhoHasItHandler(this);
		
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Log.d(TAG, "Service started!!!!");
		super.onStartCommand(intent, flags, startId);
		
		this.runFlag = true;
		this.updater.start();
		this.whoHasIt.setServiceRunning(true);
		
		return START_STICKY;
	}

	@Override
	public void onDestroy() {
		Log.d(TAG, "onDestroyed");
		super.onDestroy();
		
		this.runFlag = false;
		this.updater.interrupt();
		this.updater = null;
		this.whoHasIt.setServiceRunning(false);
	}
	

	/**
	* Thread that performs the actual update from the online service
	*/
	private class Updater extends Thread 
	{
		private NotificationManager notificationManager; 
		private Notification notification;
		
		public Updater() {
			super("WhoHasItService-Updater");
			this.notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
			this.notification = new Notification(R.drawable.icon,"", 0);
		}

		@Override
		public void run() {
			WhoHasItService whoHasItService = WhoHasItService.this;
			WhoHasItHandler whoHasItHandler = WhoHasItUtils.getWhoHasItHandler(WhoHasIt.getContext());
			while (whoHasItService.runFlag) {
				Log.d(TAG, "Updater running");
				try 
				{
					WhoHasIt whohasit = (WhoHasIt) getApplication();
					if (whohasit.isServiceRunning())
					{
						Iterator<Loan> loans = whoHasItHandler.getLoans().iterator();
						while (loans.hasNext())
						{
							Loan loan = loans.next();
							if (loan.isToLate() && !notified.contains(loan.getLoanID()))
							{
								Log.d(TAG, "We have a to late item");
								sendToLateNotification(whoHasItService, loan);
								notified.add(loan.getLoanID());
							}
							if (!loan.isToLate() && notified.contains(loan.getLoanID()))
							{
								Log.d(TAG, "We have reset a to late item");
								notified.remove(loan.getLoanID());
							}
						}
					}

					Log.d(TAG, "Updater ran");
					Thread.sleep(DELAY);
				} 
				catch (InterruptedException e) 
				{
					whoHasItService.runFlag = false;
				}
			}
		}

		private void sendToLateNotification(Context context, Loan loan) 
		{
			Log.d(TAG, "sendToLateNotification");
			Intent intent = new Intent(context, LoanActivity.class);
			intent.putExtra(Loan.LOAN_KEY, loan.getLoanID());
			PendingIntent pendingIntent = PendingIntent.getActivity(context, -1, intent,
			PendingIntent.FLAG_UPDATE_CURRENT); 
			notification.when = System.currentTimeMillis(); 
			notification.flags |= Notification.FLAG_AUTO_CANCEL; 
			CharSequence notificationTitle = context.getText(R.string.notification_to_late_title); 
			CharSequence notificationSummary = context.getString(R.string.notification_to_late_message, loan.getNotify());
			notification.setLatestEventInfo(context, notificationTitle, notificationSummary, pendingIntent); 
			notificationManager.notify(0, notification);
		}

	}
}
